package jsyf.oa.service.doc;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.doc.AttachHistoryDao;
import jsyf.oa.dao.doc.MainDao;
import jsyf.oa.dao.system.CheckDao;
import jsyf.oa.entity.doc.AttachHistoryEntity;
import jsyf.oa.entity.doc.DocMainEntity;
import jsyf.oa.entity.doc.MainEntity;
import jsyf.oa.facade.doc.MainFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/4/20.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class MainService implements MainFacade {

    @Autowired
    private MainDao mainDao;

    @Autowired
    private AttachHistoryDao attachHistoryDao;

    @Autowired
    private CheckDao checkDao;

    @Override
    public JSONObject getMainByPage(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        String departName = jsonParams.getString("departName");
        String key = jsonParams.getString("key");

        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" and companyId=?");
            sqlArgs.add(companyId);
        }
        if (!StringUtils.isBlank(departName)) {
            condition.append(" and departName=?");
            sqlArgs.add(departName);
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" and docName like ?");
            sqlArgs.add("%" + key + "%");
        }
        condition.append(" and delFlag = 0");
        condition.append(" ORDER BY createTime DESC");
        //查询list
        List<JSONObject> records = mainDao.getViewJSONListByPage(condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        //查询总数
        Integer recordCount = mainDao.getViewPageCount(condition.toString(), sqlArgs.toArray());
        //分装前端需要的格式
        int pageCount = 0;
        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / pageSize + 1);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public List<JSONObject> getMainByCompanyId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" and companyId= ? ");
            sqlArgs.add(companyId);
        }
        condition.append(" and delFlag = 0 ");
        condition.append(" ORDER BY createTime DESC ");
        //查询list
        List<JSONObject> records =
                mainDao.getViewJSONListByCondition(condition.toString(), sqlArgs.toArray());
        return records;
    }

    @Override
    public List<JSONObject> getCompanyListByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userIds = checkDao.getChilderByUserId(jsonParams.getString("userId"),true);
        StringBuilder sbSql = new StringBuilder();
        sbSql.append("select ID AS companyId,`NAME` AS companyName from t_sys_company\n" +
                "WHERE ID IN(\n" +
                "SELECT COMPANY_ID FROM t_sys_depart\n" +
                "LEFT JOIN t_sys_role on t_sys_depart.ID=t_sys_role.DEPART_ID\n" +
                "LEFT JOIN t_sys_user ON t_sys_role.ID=t_sys_user.ROLE_ID\n" +
                "WHERE t_sys_user.ID in (" + userIds + ")\n" +
                "AND t_sys_role.DEL_FLAG=0 \n" +
                "AND t_sys_depart.DEL_FLAG=0 )\n" +
                "AND ID IN (SELECT t_doc_main.COMPANY_ID FROM t_doc_main GROUP BY t_doc_main.COMPANY_ID)\n" +
                "AND t_sys_company.DEL_FLAG=0 \n" +
                "ORDER BY t_sys_company.SORT_NO");
        return mainDao.queryForJsonList(sbSql.toString());
    }

    @Override
    public JSONObject getMainDetail(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        // ( id ) = ( mainID )
        String id = jsonParams.getString("id");
        JSONObject results = new JSONObject();
        JSONObject docMain = mainDao.getViewJSONById(id);
        List<JSONObject> attachHistoryList =
                attachHistoryDao.getJSONListByCondition(" and MAIN_ID=?", new Object[]{id});
        results.put("docMain", docMain);
        results.put("attachHistoryList", attachHistoryList);
        return results;
    }

    @Override
    public String save(String jsonData) {
        DocMainEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), DocMainEntity.class);
        if ("0".equals(entity.getDocMain().getId()) || StringUtils.isBlank(entity.getDocMain().getId())) {
            mainDao.add(entity.getDocMain());
        } else {
            MainEntity mainEntity = (MainEntity) mainDao.getIBaseEntityById(entity.getDocMain().getId());
            mainEntity.setFkTypeId(entity.getDocMain().getFkTypeId());
            mainEntity.setDocName(entity.getDocMain().getDocName());
            mainEntity.setSource(entity.getDocMain().getSource());
            mainEntity.setAttachName(entity.getDocMain().getAttachName());
            mainEntity.setAttachUrl(entity.getDocMain().getAttachUrl());
            mainEntity.setImageName(entity.getDocMain().getImageName());
            mainEntity.setImageUrl(entity.getDocMain().getImageUrl());
            mainEntity.setDelFlag(entity.getDocMain().getDelFlag());
            mainEntity.setCompanyId(entity.getDocMain().getCompanyId());
            mainEntity.setDepartName(entity.getDocMain().getDepartName());
            mainEntity.setScreenType(entity.getDocMain().getScreenType());
            mainDao.update(mainEntity);
        }
        List<AttachHistoryEntity> attachModel = entity.getAttachHistoryList();
        if (attachModel != null && attachModel.size() > 0) {
            for (int i = 0; i < attachModel.size(); i++) {
                AttachHistoryEntity attach = attachModel.get(i);
                if (!StringUtils.isBlank(attach.getId())) {
                    attachHistoryDao.removeById(attach.getId());
                }
                attach.setMainId(entity.getDocMain().getId());
                attach.setAttachName(attach.getAttachName());
                attach.setAttachUrl(attach.getAttachUrl());
                attach.setImageName(attach.getImageName());
                attach.setImageUrl(attach.getImageUrl());
                attachHistoryDao.add(attach);
            }
        }
        return entity.getDocMain().getId();
    }

    @Override
    public Boolean delById(String id) {
        return mainDao.delById(id) > 0;
    }

}